package com.my.screenadapter;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;

import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.Thing;
import com.my.screenadapter.ImgVideoSel.ImgVideoSelActivity;
import com.my.screenadapter.MPerMission.MyPermission;
import com.my.screenadapter.MyLocation.MyGaoDeLocation;
import com.my.screenadapter.MyProgress.MyProgressActivity;
import com.my.screenadapter.MyRecyclerHeader.RecyclerActivity;
import com.my.screenadapter.View.EditTextActivity;
import com.my.screenadapter.View.MConstraint_layout;
import com.my.screenadapter.aidlDemo.IPCMessengerActivity;
import com.my.screenadapter.aidlDemo.IpcAIDLActivity;
import com.my.screenadapter.bundle.BundleTurnActivity;
import com.my.screenadapter.data.MmkvActivity;
import com.my.screenadapter.mService.MyServiceActivity;
import com.my.screenadapter.alarmclock.AlarmClockActivity;
import com.my.screenadapter.anim.lottie.LottieShowActivity;
import com.my.screenadapter.bluetooth.print.PrintShareActivity;
import com.my.screenadapter.eventBus.EventbusActivity;
import com.my.screenadapter.eventBus.eventBusDemo.EventBusActivity;
import com.my.screenadapter.fragmenttest.FragmentContainerActivity;
import com.my.screenadapter.hook.Hook_01Activity;
import com.my.screenadapter.lifecircle.CrashActiviyLifeDemo;
import com.my.screenadapter.lifecircle.SaveTempDataActivity;
import com.my.screenadapter.mInterface.ServiceLoader1Activity;
import com.my.screenadapter.mLruCache.MLruCacheActivity;
import com.my.screenadapter.mTextview.TTFActivity;
import com.my.screenadapter.mThread.ThreadKillActivity;
import com.my.screenadapter.mThread.ThreadSyncActivity;
import com.my.screenadapter.mdir.DirActivity;
import com.my.screenadapter.mvp.MVPActivity;
import com.my.screenadapter.myActivity.IntentActivity;
import com.my.screenadapter.myActivity.LaunchActivity;
import com.my.screenadapter.myHandler.HandlerDemoActivity;
import com.my.screenadapter.myHandler.MsgQueueActivity;
import com.my.screenadapter.myHandler.ThreadHandlerActivity;
import com.my.screenadapter.mywebview.H5WebViewActivity;
import com.my.screenadapter.mywebview.WebViewActivity;
import com.my.screenadapter.net.DownLoadActivity;
import com.my.screenadapter.net.HttpCompareActivity;
import com.my.screenadapter.net.OkHttpActivity;
import com.my.screenadapter.net.retrofit.RetrofitActivity;
import com.my.screenadapter.nobar.NoBarActivity;
import com.my.screenadapter.push.PushSetActivity;
import com.my.screenadapter.rvcommon.ListDemo.ListFirstActivity;
import com.my.screenadapter.rxjavashow.RxJavaActivity;
import com.my.screenadapter.searchpopwindow.SearchActivity;
import com.my.screenadapter.shell.ShellActivity;
import com.my.screenadapter.sql.CursorActivity;
import com.my.screenadapter.sql.SqlAddstrActivity;
import com.my.screenadapter.sql.SqlTestActivity;
import com.my.screenadapter.sql.SqliteUpdateActivity;
import com.my.screenadapter.time.MyTimeActivity;
import com.my.screenadapter.usb.UsbActivity;
import com.my.screenadapter.utils.DebugUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    // android studio 系列总结blog:插件 http://www.open-open.com/lib/view/open1480329318348.html
    private DisplayMetrics metrics;

    @BindView(R.id.rv)
    RecyclerView rv;
    private ServiceConnection connMyService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        boolean apkInDebug = DebugUtils.isApkInDebug(this);
        Log.i(TAG, "onCreate: apkInDebug: "+apkInDebug);
        jsonTest();
        setContentView(R.layout.activity_main);
        ButterKnife.bind(MainActivity.this);
        getScreenSizeOfDevice();
//        scala语言
//        LinearLayoutManager:线性布局,横向或者纵向滑动列表
//        GridLayoutManager:表格布局
//        StaggeredGridLayoutManager:流式布局,例如瀑布流效果
//        当然除了上面的三种内部布局之外，我们还可以继承RecyclerView.LayoutManager来实现一个自定义的LayoutManager。
//                recyclerView.setHasFixedSize();
//                以如当不是瀑布流时，设置这个可以避免重复的增删造成而外的浪费资源
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        rv.setLayoutManager(staggeredGridLayoutManager);
//        SparseArray mList=new SparseArray<>();

        final List<TempSave> mList = new ArrayList();
//        mList.add(new TempSave("导航栏测试  ",com.znjb.myapplication.MainActivity.class));

        mList.add(new TempSave("mmkv 多进程，多APP测试 ", MmkvActivity.class));
        mList.add(new TempSave("bundle ", BundleTurnActivity.class));
        mList.add(new TempSave("MVP ", MVPActivity.class));
        mList.add(new TempSave("okhttp ", OkHttpActivity.class));
        mList.add(new TempSave("Service", MyServiceActivity.class));
        mList.add(new TempSave("retrofit", RetrofitActivity.class));
        mList.add(new TempSave("下载测试", DownLoadActivity.class));
        mList.add(new TempSave("usbConnect  ", UsbActivity.class));
        mList.add(new TempSave("cursor  ", CursorActivity.class));
        mList.add(new TempSave("textView 更换字体 ", TTFActivity.class));
        mList.add(new TempSave("hook ", Hook_01Activity.class));
        mList.add(new TempSave("Intent 跳转生命周期，返回值", IntentActivity.class));
        mList.add(new TempSave("LruCache", MLruCacheActivity.class));
        mList.add(new TempSave("文件夹简介 and File", DirActivity.class));
        mList.add(new TempSave(" 测试thread kill", ThreadKillActivity.class));
        mList.add(new TempSave(" handlerThread", ThreadHandlerActivity.class));
        mList.add(new TempSave(" 测试同步能否不并发", ThreadSyncActivity.class));
        mList.add(new TempSave(" Shell测试del...", ShellActivity.class));
        mList.add(new TempSave("仿写 event,mainhandlerpost ", EventBusActivity.class));
        mList.add(new TempSave(" EventBus ", EventbusActivity.class));
        mList.add(new TempSave(" IpcAIDLActivity ", IpcAIDLActivity.class));
        mList.add(new TempSave(" Module间通信ServiceHandler ", IPCMessengerActivity.class));
        mList.add(new TempSave(" ServiceLoader1 ", ServiceLoader1Activity.class));
        mList.add(new TempSave(" 极光推送高级功能 ", PushSetActivity.class));
        mList.add(new TempSave(" MyTimeActivity14 ", MyTimeActivity.class));
        mList.add(new TempSave(" SqliteUpdate ", SqliteUpdateActivity.class));
        mList.add(new TempSave(" MyTimeActivity ", MyTimeActivity.class));
        // TODO: 2020/8/28 to ft smartapplication 
//        mList.add(new TempSave(" SmartSnackBar ", SnackbarActivity.class));
//        mList.add(new TempSave(" SmartToast ", TestToastActivity.class));
        mList.add(new TempSave(" H5Js互相调用 ", H5WebViewActivity.class));
        mList.add(new TempSave(" edittext编辑 ", EditTextActivity.class));
        mList.add(new TempSave(" HandlerStaticWeak ", HandlerDemoActivity.class));
        mList.add(new TempSave(" Handler对比 ,MsgQueue", MsgQueueActivity.class));
        mList.add(new TempSave(" Activity跳轉 ", LaunchActivity.class));
        mList.add(new TempSave(" Constraint_layout布局 ", MConstraint_layout.class));
        mList.add(new TempSave("CrashActiviyLifeDemo  ", CrashActiviyLifeDemo.class));
        mList.add(new TempSave("activity屏幕切换保存临时数据  ", SaveTempDataActivity.class));
        mList.add(new TempSave("SqlAddstrActivity  ", SqlAddstrActivity.class));
        mList.add(new TempSave("http对比  ", HttpCompareActivity.class));
        mList.add(new TempSave("数据库测试  ", SqlTestActivity.class));
        mList.add(new TempSave("MyGaoDeLocation", MyGaoDeLocation.class));
        mList.add(new TempSave("printshare打印", PrintShareActivity.class));
        mList.add(new TempSave("Lottie动画", LottieShowActivity.class));
        mList.add(new TempSave("RXjava应用", RxJavaActivity.class));
        mList.add(new TempSave("Fragment测试", FragmentContainerActivity.class));
        mList.add(new TempSave("状态栏变色NoActionBar", NoBarActivity.class));
        mList.add(new TempSave("webView Activity", WebViewActivity.class));
        mList.add(new TempSave("搜索Activity", SearchActivity.class));
        mList.add(new TempSave("闹钟", AlarmClockActivity.class));
        mList.add(new TempSave("6.0权限Activity", MyPermission.class));


        final MainAdapter mainAdapter = new MainAdapter(mList);
        rv.setAdapter(mainAdapter);
        mainAdapter.setData(mList);
        mainAdapter.setOnItemClickListener(new MainAdapter.ItemClickListener() {
            @Override
            public void itemClickListener(int position) {
                startActivity(new Intent(MainActivity.this, mList.get(position).getData()));
            }
        });

        rv.setHasFixedSize(true);

        new Handler().postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        int size = mList.size();
                        // TODO: 2020/8/28  暂时取消 因为迁移 androidx
//                        mList.add(new TempSave("PicSelect--->图片选择", SMainActivity.class));
//                        mList.add(new TempSave("PicSelect_hostActivity--->图片选择,base64", MImgActivity.class));

                        mList.add(new TempSave("PictureSelector---图片视频", ImgVideoSelActivity.class));
                        mList.add(new TempSave("RecyclerView添加HeaderView和FooterView", RecyclerActivity.class));
                        mList.add(new TempSave("Recyclerview对比_activity", ListFirstActivity.class));
                        mList.add(new TempSave("进度条Activity", MyProgressActivity.class));
//                        mainAdapter.notifyItemRangeInserted(0,mList.size()-size);
                        mainAdapter.notifyItemRangeInserted(size-1,mList.size()-size);
                    }
                },5000
        );

        connMyService = new ServiceConnection() {
             @Override
             public void onServiceConnected(ComponentName name, IBinder service) {
                 Log.i(TAG, "onServiceConnected: ");
             }

             @Override
             public void onServiceDisconnected(ComponentName name) {
                 Log.i(TAG, "onServiceDisconnected: ");
             }
         };

        TestSingleInstance instance = TestSingleInstance.getInstance();
        Log.i(TAG, "onCreate: instance mainac "+instance.hashCode());
        Log.i(TAG, "onCreate: application instance "+ MyApplication.getInstance().hashCode());
//        Intent intent = new Intent(this, MyService.class);
//        Bundle bundle = new Bundle();
//        bundle.putString("mac","abc");
//        intent.putExtras(bundle);
//        bindService(intent, connMyService,BIND_AUTO_CREATE);

    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
//        unbindService(connMyService);
    }

    //json解析测试 键值对
    private void jsonTest() {
        String data = "{\"lifecircle\":[{\"100002\":\"苯醚·噻霉酮\"},{\"100008\":\"氢氧化铜\"},{\"100009\":\"琥胶肥酸铜\"},{\"100010\":\"春雷·王铜\"},{\"100011\":\"春雷霉素\"},{\"100012\":\"氯溴异氰尿酸\"}]}";
        try {
            JSONObject jsonObject = new JSONObject(data);
            JSONArray array = jsonObject.getJSONArray("lifecircle");
            for (int i = 0; i < array.length(); i++) {
                JSONObject object2 = array.getJSONObject(i);
                //Caused by: java.lang.ClassCastException: org.json.JSONObject cannot be cast to java.util.Map
//                Map<String, Object> map = (Map<String, Object>) object2;
//                for (Map.Entry<String, Object> entry : map.entrySet()) {
//                    Log.i("json=====",entry.getKey()+"="+entry.getValue());
//                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    public void viewsActivity(View view) {
        startActivity(new Intent(this,MainViewsActivity.class));
    }

    /**
     * recycler view bean
     */
    class TempSave {
        String name;
        Class<?> data;

        public TempSave(String name, Class<?> data) {
            this.name = name;
            this.data = data;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Class<?> getData() {
            return data;
        }

        public void setData(Class<?> data) {
            this.data = data;
        }
    }



    //    三星平板    适配的640dp
//    屏幕密度===: 320
//    density,1dip相当于多少个px===: 2.0
//    宽度===px: 1600===dp=800.0
//    高度===px: 2560===dp=1280.0
//
//    三星平板 Galaxy Tab S2 SM-T819C
//    12-10 11:51:40.390 5875-5875/com.my.screenadapter I/屏幕密度===: 320
//            12-10 11:51:40.390 5875-5875/com.my.screenadapter I/density,1dip相当于多少个px===: 2.0
//            12-10 11:51:40.390 5875-5875/com.my.screenadapter I/宽度===px: 1536===dp=768.0
//            12-10 11:51:40.390 5875-5875/com.my.screenadapter I/高度===px: 2048===dp=1024.0
//            12-10 11:51:40.390 5875-5875/com.my.screenadapter I/获得屏幕英寸===: 8.0
//    华为荣耀 4X 适配的360dp
//    10-11 09:39:07.010 24130-24130/com.my.screenadapter I/屏幕密度===: 320
//            10-11 09:39:07.010 24130-24130/com.my.screenadapter I/density,1dip相当于多少个px===: 2.0
//            10-11 09:39:07.010 24130-24130/com.my.screenadapter I/宽度===px: 720===dp=360.0
//            10-11 09:39:07.010 24130-24130/com.my.screenadapter I/高度===px: 1280===dp=640.0
//    酷派   适配的360dp
//    10-11 10:03:09.178 7662-7662/com.my.screenadapter I/屏幕密度===: 240
//            10-11 10:03:09.178 7662-7662/com.my.screenadapter I/density,1dip相当于多少个px===: 1.5
//            10-11 10:03:09.178 7662-7662/com.my.screenadapter I/宽度===px: 540===dp=360.0
//            10-11 10:03:09.178 7662-7662/com.my.screenadapter I/高度===px: 960===dp=640.0
//            10-11 10:03:09.179 7662-7662/com.my.screenadapter I/获得屏幕英寸===: 4.589389937671455
//     华为p9
// 12-10 15:35:31.283 24851-24851/com.my.screenadapter I/屏幕密度===: 480
//            12-10 15:35:31.283 24851-24851/com.my.screenadapter I/density,1dip相当于多少个px===: 3.0
//            12-10 15:35:31.283 24851-24851/com.my.screenadapter I/宽度===px: 1080===dp=360.0
//            12-10 15:35:31.283 24851-24851/com.my.screenadapter I/高度===px: 1812===dp=604.0
//            12-10 15:35:31.283 24851-24851/com.my.screenadapter I/获得屏幕英寸===: 4.394670067251921
    private void getScreenSizeOfDevice() {
        //display包含了屏幕尺寸和分辨率 这样的信息
        Display display = getWindowManager().getDefaultDisplay();
        //描述了屏幕的尺寸，分辨率，字体大小等信息
        metrics = new DisplayMetrics();
        //经过一个测量得到屏幕的尺寸和分辨率
        display.getMetrics(metrics);
        Log.i("屏幕整体密度===", metrics.densityDpi + "");
        Log.i("density,1dip相当于多少个px===", metrics.density + "");
        Log.i("宽度===px", metrics.widthPixels + "dp=" + metrics.widthPixels / metrics.density);
        Log.i("高度===px", metrics.heightPixels + "dp=" + metrics.heightPixels / metrics.density);

        DisplayMetrics dm = getResources().getDisplayMetrics();
        int width = dm.widthPixels;
        int height = dm.heightPixels;
        double x = Math.pow(width, 2);
        double y = Math.pow(height, 2);
        double diagonal = Math.sqrt(x + y);

        int dens = dm.densityDpi;
        double screenInches = diagonal / (double) dens;
        Log.i("获得屏幕英寸===", "" + screenInches);
        Log.i("获得屏幕英寸===", "" + screenInches);
    }

    private void getScreenSizeOfDevice2() {
        double x = Math.pow(metrics.widthPixels / metrics.xdpi, 2);
        double y = Math.pow(metrics.heightPixels / metrics.ydpi, 2);
        double screenInches = Math.sqrt(x + y);
        Log.d("获得屏幕英寸===", screenInches + "");
        Log.d("获得屏幕英寸===", screenInches + "");
    }
}
